<?php //echo "<pre>"; print_r($pBarang);die();?>
<?php $this -> load -> view('header'); ?>
<!-- BEGIN CONTAINER -->
<div class="page-container row-fluid">
	<?php $this->load->view('sidebar');?>
	<!-- BEGIN PAGE -->
	<div class="page-content">
		<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
		<div id="portlet-config" class="modal hide">
			<div class="modal-header">
				<button data-dismiss="modal" class="close" type="button"></button>
				<h3>portlet Settings</h3>
			</div>
			<div class="modal-body">
				<p>
					Here will be a configuration form
				</p>
			</div>
		</div>
		<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
		<!-- BEGIN PAGE CONTAINER-->
		<div class="container-fluid">
			<!-- BEGIN PAGE HEADER-->
			<div class="row-fluid">
				<div class="span12">
					<!-- BEGIN STYLE CUSTOMIZER -->
					<div class="color-panel hidden-phone">
						<div class="color-mode-icons icon-color"></div>
						<div class="color-mode-icons icon-color-close"></div>
						<div class="color-mode">
							<p>
								THEME COLOR
							</p>
							<ul class="inline">
								<li class="color-black current color-default" data-style="default"></li>
								<li class="color-blue" data-style="blue"></li>
								<li class="color-brown" data-style="brown"></li>
								<li class="color-purple" data-style="purple"></li>
								<li class="color-white color-light" data-style="light"></li>
							</ul>
							<label class="hidden-phone">
								<input type="checkbox" class="header" checked value="" />
								<span class="color-mode-label">Fixed Header</span> </label>
						</div>
					</div>
					<!-- END BEGIN STYLE CUSTOMIZER -->

					<!-- BEGIN PAGE TITLE & BREADCRUMB-->
					<h3 class="page-title"> Category <small>Barang</small></h3>
					<?php $this -> load -> view('breadcrumb'); ?>
					<!-- END PAGE TITLE & BREADCRUMB-->
				</div>
			</div>
			<!-- END PAGE HEADER-->
			<!-- BEGIN PAGE CONTENT-->
			<div class="row-fluid">
				<div class="span12">
					<!-- BEGIN EXAMPLE TABLE PORTLET-->
					<div class="portlet box blue">
						<div class="portlet-title">
							<h4><i class="icon-edit"></i>Category List</h4>
							<!--<div class="tools" >
								<a href="javascript:;" class="reload"></a>
							</div>-->
														
							<div class="actions" style="padding-right: 0px">
								<!--<a href="<?php echo base_url()?>category/createEdit" class="btn green"><i class="icon-plus"></i> Add</a>								
								<a href="#" class="btn green"><i class="icon-print"></i> Print</a>
								<a href="#" class="btn green"><i class="icon-tasks"></i> Pdf</a>
								<a href="#" class="btn green"><i class="icon-envelope"></i> Excel</a>-->								
							</div>
							
						</div>
						<div class="portlet-body">
							<?php //$this->load->view('searchBar', $searchBar);?>
							<!-- TREE VIEW CATEGORY -->
							<!-- Definition of context menu -->
						  <ul id="myMenu" class="contextMenu">
						    <li class="copy"><a href="#add">Add Child</a></li>
						    <li class="edit separator"><a href="#edit">Edit Node</a></li>
						    <li class="delete"><a href="#delete">Delete</a></li>
						    <li class="quit separator"><a href="#quit">Quit</a></li>
						  </ul>

					  <!-- Definition tree structure -->
						  <div id="tree">
						    
						  </div>

  							<div>Selected node: <span id="echoActivated">-</span></div>
							<div class="row-fluid">
							  <form id="formAddCatByParent" class="form-horizontal"> 		
								<div id="myModal3" class="modal hide fade"  tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
									<div class="modal-header" >
										<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
										<h3 id="myModalLabel3">Confirm Header</h3>
									</div>
									<div class="modal-body" align="left">
										<div id="loadingImage" style="display: none">
											<img src="<?php echo base_url()?>assets/dynatree/css/loading.gif" />
										</div>
										<div id="alert" class="alert alert-error" style="display: none">											
										</div>
										<input type="hidden" name="id" id="id" value="0"/>
										<input type="hidden" name="parent" id="parent"/>
										<input type="hidden" name="level" id="level" value="0"/>
										
										<div class="control-group">
	                                       <label class="control-label">Name</label>
	                                       <div class="controls">
	                                          <input type="text" name="name" id="name" class="m-wrap medium" placeholder="category name">
	                                          <span class="help-inline small"><i>*name of category must uniq</i></span>
	                                       </div>
	                                    </div>
									</div>
									<div class="modal-footer">
										<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
										<button type="submit" class="btn blue">Confirm</button>
									</div>
								</div>
							  </form>
							  <div id="alertDelete" class="modal hide fade" style="width:300px" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
									<div class="modal-header" >
										<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
										<h3 id="myModalLabel3">Remove</h3>
									</div>
									<div class="modal-body" align="left">
									<div id="loadingImage2" style="display: none">
											<img src="<?php echo base_url()?>assets/dynatree/css/loading.gif" />
									</div>
									<div id="alert2" class="alert alert-error" style="display: none">											
									</div>
										Are You Sure ?
									</div>
									<input type="hidden" id="sel_node" />
									<div class="modal-footer">
										<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
										<button id="btnDelete" class="btn blue">Confirm</button>
										<button id="btnForceDelete" class="btn blue">Force Delete</button>
									</div>
								</div>	
							</div>
						</div>
						
						
					</div>
					<!-- END EXAMPLE TABLE PORTLET-->
				</div>
			</div>			
				<!-- END PAGE CONTENT -->
		</div>
		<!-- END PAGE CONTAINER-->
	</div>
	<!-- END PAGE -->
</div>
<!-- END CONTAINER -->

<?php $this->load->view('footer')?>

 <script type="text/javascript">

  // --- Implement Cut/Copy/Paste --------------------------------------------
  var clipboardNode = null;
  var pasteMode = null;
  var selNode = null;
  
  function copyPaste(action, node) {
    switch( action ) {
    case "cut":
    case "copy":
      clipboardNode = node;
      pasteMode = action;
      break;
    case "paste":
      if( !clipboardNode ) {
        alert("Clipoard is empty.");
        break;
      }
      if( pasteMode == "cut" ) {
        // Cut mode: check for recursion and remove source
        var isRecursive = false;
        var cb = clipboardNode.toDict(true, function(dict){
          // If one of the source nodes is the target, we must not move
          if( dict.key == node.data.key )
            isRecursive = true;
        });
        if( isRecursive ) {
          alert("Cannot move a node to a sub node.");
          return;
        }
        node.addChild(cb);
        clipboardNode.remove();
      } else {
        // Copy mode: prevent duplicate keys:
        var cb = clipboardNode.toDict(true, function(dict){
          dict.title = "Copy of " + dict.title;
          delete dict.key; // Remove key, so a new one will be created
        });
        node.addChild(cb);
      }
      clipboardNode = pasteMode = null;
      break;
    default:
      alert("Unhandled clipboard action '" + action + "'");
    }
  };

  function addChild(action, node){
  		$("#myModal3").modal('show');
  		$('#parent').val(node.data.code);
  		$('#level').val(node.getKeyPath());		  
  };
  
  function editNode(node){
  		$.ajax({
		  url: "http://localhost/eInvento/category/getById/"+node.data.code,
		  success: function(data){
		  	 	if (data.category != null){
		  	 		$('#id').val(data.category.code);
		  	 		$('#name').val(data.category.name);
		  	 		$('#parent').val(data.category.parent);
		  	 		//alert(data.category.code + " " + data.category.name + " " + data.category.parent);
		  	 	}
		  },
		  dataType: "json"
		});
  		$("#myModal3").modal('show');  				  
  };
  
  function removeNode(node){
  		$("#alertDelete").modal('show');
  		$('#loadingImage2').hide();
	    $('#alert2').hide();
  		selNode = node;
  		  			
  }
  
  $('#btnDelete').click(function(){
  		$('#loadingImage2').show();
	    $('#alert2').hide();
  		$.ajax({
		  url: "http://localhost/eInvento/category/remove/"+selNode.data.code,
		  success: function(data){
		  	 	$('#loadingImage2').hide();
		  		if (data.error == 1){
		  			var html = '<strong>Error!</strong> ' + data.errorMsg;
					$('#alert2').html(html);	
					$('#alert2').show();						
		  		} 
		  		
		  	 	if (data.success == 1){
		  	 		$('#alertDelete').modal('hide');
		  			 $.gritter.add({
	                	title: 'Success!',
	                	text: data.successMsg
	            	});
	            	selNode.remove();
		  	 	}
		  },
		  dataType: "json"
		});
  });
  
  $('#btnForceDelete').click(function(){
  		$('#loadingImage2').show();
	    $('#alert2').hide();
  		$.ajax({
		  url: "http://localhost/eInvento/category/remove/"+selNode.data.code+"/TRUE",
		  success: function(data){
		  	 	$('#loadingImage2').hide();
		  		if (data.error == 1){
		  			var html = '<strong>Error!</strong> ' + data.errorMsg;
					$('#alert2').html(html);	
					$('#alert2').show();						
		  		} 
		  		
		  	 	if (data.success == 1){
		  	 		$('#alertDelete').modal('hide');
		  			 $.gritter.add({
	                	title: 'Success!',
	                	text: data.successMsg
	            	});
	            	selNode.remove();
		  	 	}
		  },
		  dataType: "json"
		});
  });
  
  $("#myModal3").draggable({
      handle: ".modal-header"
  }); 
  
  $("#formAddCatByParent").submit(function(event) {
 
	  /* stop form from submitting normally */
	  event.preventDefault();
	  
	  $('#loadingImage').show();
	  $('#alert').hide();
	  //$('#alert').show();
	 
	  /* get some values from elements on the page: */
	  var $form = $( this ),
	      term = $(this).serialize(),
	      url = $form.attr( 'action' );
	 
	  /* Send the data using post */
	  var posting = $.post( "http://localhost/eInvento/category/save", term,"json"
	  					  );
	 
	  /* Put the results in a div */
	  posting.done(function( data ) {
	  		$('#loadingImage').hide();
	  		if (data.error == 1){
	  			var html = '<strong>Error!</strong> ' + data.errorMsg;
				$('#alert').html(html);	
				$('#alert').show();						
	  		} 
	  		
	  		if (data.success == 1){
	  			$('#myModal3').modal('hide');
	  			 $.gritter.add({
                // (string | mandatory) the heading of the notification
                	title: 'Success!',
                // (string | mandatory) the text inside the notification
                	text: data.successMsg
            	});
				
				$("#tree").dynatree("getTree").reload();
           		return false;
	  		}
	  });
	  
	  posting.error(function(){
           alert('failure');        
      });   
	});
 /* $( "#myModal3" ).dialog({
      autoOpen: false,
      height: 300,
      width: 350,
      modal: true
 }); */
  
  // --- Contextmenu helper --------------------------------------------------
  function bindContextMenu(span) {
    // Add context menu to this node:
    $(span).contextMenu({menu: "myMenu"}, function(action, el, pos) {
      // The event was bound to the <span> tag, but the node object
      // is stored in the parent <li> tag
      var node = $.ui.dynatree.getNode(el);
      switch( action ) {
      case "add": addChild(action, node);break;
      case "edit": 	editNode(node);
      				break;
      case "delete": removeNode(node);break;
      case "paste":
        copyPaste(action, node);
        break;
      default:
        alert("Todo: appply action '" + action + "' to node " + node);
      }
    });
  };

  // --- Init dynatree during startup ----------------------------------------

  $(function(){

    $("#tree").dynatree({
      persist: true,
      onActivate: function(node) {
        $("#echoActivated").text(node.data.title + ", key=" + node.data.code);
                 
      },
      initAjax: {
        url: "http://localhost/eInvento/category/getChild/0"
       },
      onClick: function(node, event) {
        // Close menu on click
        if( $(".contextMenu:visible").length > 0 ){
          $(".contextMenu").hide();
//          return false;
        }
      },
      onKeydown: function(node, event) {
        // Eat keyboard events, when a menu is open
        if( $(".contextMenu:visible").length > 0 )
          return false;

        switch( event.which ) {

        // Open context menu on [Space] key (simulate right click)
        case 32: // [Space]
          $(node.span).trigger("mousedown", {
            preventDefault: true,
            button: 2
            })
          .trigger("mouseup", {
            preventDefault: true,
            pageX: node.span.offsetLeft,
            pageY: node.span.offsetTop,
            button: 2
            });
          return false;

        // Handle Ctrl-C, -X and -V
        case 67:
          if( event.ctrlKey ) { // Ctrl-C
            copyPaste("copy", node);
            return false;
          }
          break;
        case 86:
          if( event.ctrlKey ) { // Ctrl-V
            copyPaste("paste", node);
            return false;
          }
          break;
        case 88:
          if( event.ctrlKey ) { // Ctrl-X
            copyPaste("cut", node);
            return false;
          }
          break;
        }
      },
      /*Bind context menu for every node when it's DOM element is created.
        We do it here, so we can also bind to lazy nodes, which do not
        exist at load-time. (abeautifulsite.net menu control does not
        support event delegation)*/
      onCreate: function(node, span){
        bindContextMenu(span);
      },
      /*Load lazy content (to show that context menu will work for new items too)*/
      onLazyRead: function(node){
        node.appendAjax({
          url: "http://localhost/eInvento/category/getChild/" + node.data.code
        });
      },
    /* D'n'd, just to show it's compatible with a context menu.
       See http://code.google.com/p/dynatree/issues/detail?id=174 */
    dnd: {
      preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
      onDragStart: function(node) {
        return true;
      },
      onDragEnter: function(node, sourceNode) {
        if(node.parent !== sourceNode.parent)
          return false;
        return ["before", "after"];
      },
      onDrop: function(node, sourceNode, hitMode, ui, draggable) {
        sourceNode.move(node, hitMode);
      }
    }
    });
  });
</script>